package biz.yfsoft.app.fastframework.plugin.qiniu;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import biz.yfsoft.app.fastframework.bo.Bo;
import biz.yfsoft.app.fastframework.core.Fast;
import biz.yfsoft.app.fastframework.core.document.DocumentSaveHex;
import biz.yfsoft.app.fastframework.core.document.LocalDocument;
import biz.yfsoft.app.fastframework.kit.DataKit;
import biz.yfsoft.app.fastframework.kit.FileKit;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;

/**
 * 上传文档使用到的组件
 * @author Yfsoft
 *
 */
public class QiniuDocument extends LocalDocument{

	private final Logger logger = LoggerFactory.getLogger(getClass());
	
	@Override
	public void save(String path,Bo fRecord) throws DocumentSaveHex{
		super.save(path, fRecord);
		try {
        	byte[] data = FileKit.toByteArray(fRecord.getStr("path"));
        	upload(data,null,fRecord);
		} catch ( QiniuException e) {
			logger.error(e.getMessage());
			throw new DocumentSaveHex(e.getMessage());
		} catch (IOException e) {
			logger.error(e.getMessage());
			throw new DocumentSaveHex(e.getMessage());
		}
	}
	
	@Override
	public void saveSync(String path,Bo fRecord) throws DocumentSaveHex{
		super.save(path, fRecord);
		Fast.AynTask(new Runnable(){
			@Override
			public void run() {
				try {
		        	byte[] data = FileKit.toByteArray(fRecord.getStr("path"));
		        	upload(data,null,fRecord);
				} catch ( QiniuException e) {
					logger.error(e.getMessage());
				} catch (IOException e) {
					logger.error(e.getMessage());
				}
			}
    	});
	}
	
	/**
	 * 上传到七牛云存储
	 * @param data 字节数组
	 * @param key
	 * @param fRecord
	 * @throws QiniuException
	 */
	public void upload(byte[] data,String key,Bo fRecord) 
			throws QiniuException{
		String token = fRecord.getStr("token");
		Response res = QiniuPlugin.uploadManager.put(data, null, token);
		String retStr = res.bodyString();
		JSONObject json = JSONObject.parseObject(retStr);
		String hash = json.getString("hash");
		fRecord.set("hash", hash);
		fRecord.set("mode", "QINIU");
		fRecord.set(Bo.UPDATE_TIME, System.currentTimeMillis());
		fRecord.setStatus(1);
		fRecord.set("url",QiniuPlugin.DOMAIN + "/"+hash );
		Db.update("sys_file", fRecord);
	}
	
	@Override
	public void save(InputStream in, Bo fRecord) throws DocumentSaveHex {
		super.save(in, fRecord);
		try {
        	byte[] data = FileKit.toByteArray(in);
        	upload(data,null,fRecord);
		} catch ( QiniuException e) {
			throw new DocumentSaveHex(e.getMessage());
		} catch (IOException e) {
			throw new DocumentSaveHex(e.getMessage());
		}
	}




	@Override
	public String getToken() {
		
        return QiniuPlugin.getUpToken();
	}

	@Override
	public void loadToLocal(String key,String path) throws IOException{
		File f = new File(path);
		if(f.exists()){
			throw new IOException("File Exists! Can't Write!");
		}
		byte[] data = loadToMemory(key);
		FileOutputStream fos = new FileOutputStream(f);
		fos.write(data);
		fos.flush();
		fos.close();
	}

	@Override
	public byte[] loadToMemory(String key) throws IOException {
		String url = QiniuPlugin.DOMAIN+"/"+key;
		return DataKit.getRemoteFileData(url);
	}

	@Override
	public byte[] loadToMemory(int fileId) throws IOException {
		Record r = Db.findById("sys_file", fileId);
		String url = r.getStr("url");
		return DataKit.getRemoteFileData(url);
	}
	
	

}
